$(function () {
	// 获取商品分类并渲染到页面
	axios.get("http://localhost:9000/goods/category").then(function (res) {
		if (res.data.code === 1) {
			let html = '<li class="active">全部</li>';
			res.data.list.forEach(function (item, index) {
				html += `<li>${item}</li>`;
			});
			$(".category").html(html);
		} else {
			alert(res.data.message);
		}
	});
	// 定义请求参数
	let params = {
		current: 1,
		pagesize: 12,
		category: "",
		filter: "",
		saleType: 10,
		sortType: "id",
		sortMethod: "ASC",
		search: "",
	};

	function firstAndLastDisable() {
		if (params.current === 1) {
			$(".first").addClass("disable");
			$(".prev").addClass("disable");
		} else {
			$(".first").removeClass("disable");
			$(".prev").removeClass("disable");
		}

		if (params.current !== totalPage) {
			$(".last").removeClass("disable");
			$(".next").removeClass("disable");
		} else {
			$(".last").addClass("disable");
			$(".next").addClass("disable");
		}
	}

	// 绑定点击事件
	$(".category").on("click", "li", function () {
		$(".category li").removeClass("active");
		$(this).addClass("active");
		params.category = $(this).text();
		if (params.category === "全部") params.category = "";
		params.current = 1;
		getList();
	});
	// 使用箭头函数和ES6语法为.saleBox内的li元素绑定点击事件
	document.addEventListener("click", event => {
		if (!event.target.matches(".saleBox li")) return;
		const activeClass = "active";
		document
			.querySelectorAll(".saleBox li")
			.forEach(li => li.classList.remove(activeClass));
		event.target.classList.add(activeClass);
		params.saleType = event.target.dataset.type;
		params.current = 1;
		getList();
	});

	document.addEventListener("click", event => {
		if (!event.target.matches(".hotBox li")) return;
		const activeClass = "active";
		document
			.querySelectorAll(".hotBox li")
			.forEach(li => li.classList.remove(activeClass));
		event.target.classList.add(activeClass);
		params.filter = event.target.dataset.type;
		params.current = 1;
		getList();
	});

	document.addEventListener("click", event => {
		if (!event.target.matches(".sortBox li")) return;
		const activeClass = "active";
		document
			.querySelectorAll(".sortBox li")
			.forEach(li => li.classList.remove(activeClass));
		event.target.classList.add(activeClass);
		params.sortType = event.target.dataset.type;
		params.sortMethod = event.target.dataset.method;
		params.current = 1;
		getList();
	});

	document.addEventListener(
		"click",
		event => {
			if (event.target.matches(".next")) {
				if (params.current < totalPage) {
					params.current++;
					document.querySelector(".prev").classList.remove("disable");
					getList();
				}
			} else if (event.target.matches(".prev")) {
				if (params.current > 1) {
					params.current--;
					if (params.current === 1) {
						document.querySelector(".prev").classList.add("disable");
					}
					getList();
				}
			}
		},
		false
	);

	// 搜索框事件
	$(".search").on("blur", function () {
		params.search = this.value;
		getList();
	});

	// 跳转到指定页码
	$(".go").on("click", function () {
		let pageNum = parseInt($(".jump").val(), 10);
		if (!isNaN(pageNum) && pageNum > 0) {
			params.current = pageNum;
			getList();
		} else {
			alert("请输入有效的页码");
		}
	});

	// 每页显示数量变更
	$(".pagesize").on("change", function () {
		params.pagesize = parseInt($(this).val(), 10);
		params.current = 1;
		getList();
	});

	$(".first").on("click", function () {
		params.current = 1;
		getList();
		$(this).addClass("disable");
	});

	$(".last").on("click", function () {
		params.current = totalPage;
		getList();
		$(this).addClass("disable");
	});

	// 获取商品列表
	function getList() {
		axios
			.get("http://localhost:9000/goods/list", { params: params })
			.then(function (res) {
				if (res.data.code === 1) {
					let html = res.data.list
						.map(function (product) {
							return `
                      <li data-id="${product.goods_id}">
                          <div class="show">
                              <img src="${product.img_big_logo}">
                              ${
																product.is_hot
																	? '<span class="hot">热销</span>'
																	: ""
															}
                              ${product.is_sale ? "<span>折扣</span>" : ""}
                          </div>
                          <div class="info">
                              <p class="title">${product.title}</p>
                              <p class="price">
                                  <span class="curr">¥${
																		product.current_price
																	}</span>
                                  <span class="old">¥${product.price}</span>
                              </p>
                          </div>
                      </li>
                  `;
						})
						.join("");
					$(".list.container").html(html);
					$(".total").text(`${params.current}/${res.data.total}`);
					totalPage = res.data.total; // 更新总页数
					firstAndLastDisable();
				} else {
					alert(res.data.message);
				}
			});
	}

	getList(); // 初始加载商品列表

	// 商品详情点击事件
	$(".list.container").on("click", "li", function () {
		let id = $(this).data("id");
		sessionStorage.setItem("selectedProductId", id);
		window.location.href = "./detail.html";
	});
});
